/*************************************************************************
> File Name: socket.c
> Author: hzy
> Created Time: 2023-09-18 17:11:13
> Description:客户端
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    // 1、创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        exit(-1);
    }

    // 2、定义接收方的相关信息
    struct sockaddr_in send_addr;
    // 使用IPV4协议
    send_addr.sin_family = AF_INET;
    // 接受方的端口号
    send_addr.sin_port = htons(10086);
    // 接受方的ip地址
    send_addr.sin_addr.s_addr = inet_addr("10.7.178.214");

    while (1)
    {
        // 3、发消息
        char send_buf[128] = {0};
        printf("你要发啥子消息:");
        fflush(stdout);
        scanf("%s", send_buf);
        int ret = sendto(sockfd,
                         send_buf,
                         strlen(send_buf),
                         0,
                         (struct sockaddr *)&send_addr,
                         sizeof(send_addr));
        if (ret < 0)
        {
            perror("sendto");
            return -1;
        }

        // 4、接受消息
        char recv_buf[128] = {0};
        struct sockaddr_in recv_addr;
        socklen_t recv_len = sizeof(recv_addr);
        char ip_src[128] = {};

        int recv_ret = recvfrom(sockfd,
                                recv_buf,
                                sizeof(recv_buf),
                                0,
                                (struct sockaddr *)&recv_addr,
                                &recv_len);
        if (recv_ret < 0)
        {
            perror("recvfrom");
            break;
        }

        // 提取发送方地址
        printf("谁回显的消息\n");
        inet_ntop(AF_INET, &recv_addr.sin_addr.s_addr, ip_src, INET_ADDRSTRLEN);
        printf("ip: %s | port: %d\n", ip_src, ntohs(recv_addr.sin_port));
        printf("data(length=%ld):%s\n", strlen(recv_buf), recv_buf);
        printf("\n");
    }

    close(sockfd);

    return 0;
}